package sdk

import (
	"crypto/hmac"
	"crypto/sha1"
	"encoding/base64"
	"net/url"
	"sort"
	"strings"
)

func percentEncode(value string) string {
	// 使用url.QueryEscape进行URL编码
	encoded := url.QueryEscape(value)
	// 按照规则将编码后的字符进行替换
	encoded = strings.Replace(encoded, "+", "%20", -1)
	encoded = strings.Replace(encoded, "*", "%2A", -1)
	encoded = strings.Replace(encoded, "%7E", "~", -1)
	return encoded
}

func constructCanonicalQueryString(params map[string]string) string {
	var paramList []string

	// 按字典顺序对参数名称进行排序
	keys := make([]string, 0, len(params))
	for key := range params {
		keys = append(keys, key)
	}
	sort.Strings(keys)

	// 构建参数键值对
	for _, key := range keys {
		param := key + "=" + percentEncode(params[key])
		paramList = append(paramList, param)
	}

	// 使用"&"连接参数键值对
	return strings.Join(paramList, "&")
}

func constructStringToSign(httpMethod, canonicalQueryString string) string {
	return httpMethod + "&%2F&" + percentEncode(canonicalQueryString)
}

func calculateSignature(stringToSign, accessKeySecret string) string {
	key := accessKeySecret + "&"
	h := hmac.New(sha1.New, []byte(key))
	h.Write([]byte(stringToSign))
	signatureBytes := h.Sum(nil)
	return base64.StdEncoding.EncodeToString(signatureBytes)
}

